package edu.cs.usask.ca.silver.util.parsers.fileparsers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

import org.apache.log4j.Logger;

/**
 * This class read the folder path and create Jar from the folder with the
 * desired file name
 * 
 * @author Yudi Xue
 * 
 */
public final class JarBuilder {

	private static int BUFFER_SIZE = 10240;
	private static Logger logger = Logger.getLogger(JarBuilder.class);

	public static File createJar(String classFileLocation, String fileName)
			throws Exception {

		// get package name
		// String[] temp;
		logger.info("classfile location is:" + classFileLocation);
		// if(PlatformHelper.isMac()) {
		// temp = classFileLocation.split(File.separator);
		// } else {
		// File
		// temp = classFileLocation.trim().split("\\", 100);
		// }
		// String packageName = temp[temp.length - 1];

		File result = new File(fileName + ".jar");
		File folder = new File(classFileLocation);
		if (!folder.canRead()) {
			return null;
		}
		File[] listOfFiles = folder.listFiles();

		byte buffer[] = new byte[BUFFER_SIZE];
		FileOutputStream stream = new FileOutputStream(result);
		JarOutputStream out = new JarOutputStream(stream, new Manifest());
		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i] == null || !listOfFiles[i].exists()
					|| listOfFiles[i].isDirectory())
				continue; // Just in case...
			logger.info("Adding " + listOfFiles[i].getName());

			// Add archive entry

			JarEntry jarAdd = new JarEntry(folder.getName() + "/"
			// + System.getProperty("file.separator")
					+ listOfFiles[i].getName());
			jarAdd.setTime(listOfFiles[i].lastModified());
			out.putNextEntry(jarAdd);

			// Write file to archive
			FileInputStream in = new FileInputStream(listOfFiles[i]);
			while (true) {
				int nRead = in.read(buffer, 0, buffer.length);
				if (nRead <= 0)
					break;
				out.write(buffer, 0, nRead);
			}
			in.close();
		}

		out.close();
		stream.close();
		logger.info("Adding completed OK");

		return result;
	}

}
